package com.sto.stoapp.thread;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.sto.stoapp.activity.R;

/**
 * 蓝牙检测线程
 * 
 * @author mgf
 * 
 */
public class BlueTestThread extends BaseThread {

	private static final int MAX_COUNT = 40;

	private static final long DELAY_TIME = 2000;

	// 蓝牙测试结果
	public static final int BLUE_RESULT = 0xde;

	private BluetoothAdapter mBluetoothAdapter;

	private Handler blueHandler;

	public BlueTestThread(Context context, BluetoothAdapter mBluetoothAdapter,
			Handler blueHandler) {
		super(context);
		this.mBluetoothAdapter = mBluetoothAdapter;
		this.blueHandler = blueHandler;
	}

	@Override
	public void run() {
		super.run();
		int count = 0;
		if (!mBluetoothAdapter.isEnabled()) {
			mBluetoothAdapter.enable();
		}
		while (!mBluetoothAdapter.isEnabled() && count < MAX_COUNT) {
			mBluetoothAdapter.enable();
			try {
				Thread.sleep(DELAY_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			count++;
		}
		Message msg = blueHandler.obtainMessage();
		msg.what = BLUE_RESULT;
		if (count == MAX_COUNT) {
			msg.arg1 = R.string.blue_scan_failure;
		} else {
			msg.arg1 = R.string.blue_scan_success;
		}
		mBluetoothAdapter.disable();
		blueHandler.sendMessage(msg);
	}

}
